<?php
namespace app\api\controller;
use think\Controller;
use think\Db;

class Coupon extends Controller{
    //优惠券模块
    //优惠券列表
    public function couponList(){
        $page = input('post.page');
        if($page){if(!is_numeric($page)){return json_encode(['code'=>401,'msg'=>'page参数类型错误']);}}else{$page = 0;}
        $user_id = input('post.user_id');
        // $user_id = 3;
        if(!is_numeric($user_id)){return json_encode(['code'=>401,'msg'=>'user_id类型错误']);}
        $current_time = time();
        $coupon_list = db('coupons')->field('coupons_id,name,coupons_type,scope,number,receive_number,limits,start_time,settlement_time')
                                    ->where("area = 0 AND state = 1 AND (start_time < {$current_time} AND settlement_time > {$current_time})")
                                    ->order("add_time desc")
                                    ->limit($page*6,6)
                                    ->select();
        // echo db('coupons')->getLastSql();die; 
        // foreach($coupon_list as $k=>$vo){
        //     //仅显示有效期范围内的优惠券
        //     if($vo['start_time'] > time()){unset($coupon_list[$k]);}
        //     if($vo['settlement_time'] < time()){unset($coupon_list[$k]);}
        // }
        foreach($coupon_list as $key=>$value){
            $coupon_list[$key]['start_time'] = date("Y.m.d",$value['start_time']);
            $coupon_list[$key]['settlement_time'] = date("Y.m.d",$value['settlement_time']);
            $coupon_list[$key]['receiving_rate'] = floor(($value['receive_number']/$value['number'])*100);//优惠券已抢概率
            //优惠券使用信息
            $coupon_use_id = db('coupons_use')->where("coupons_id = {$value['coupons_id']} AND user_id = {$user_id} AND state = 0")->value('use_id');
            if($coupon_use_id){
                $coupon_list[$key]['receiving_state'] = 1;//1表示已领取该种优惠券
                $coupon_list[$key]['use_id'] = $coupon_use_id;//使用优惠券时所要提交id
            }else{
                $coupon_list[$key]['receiving_state'] = 0;
            }
        }
        // var_dump($coupon_list);die;
        if($coupon_list){
            return json_encode(['code'=>200,'msg'=>'请求成功','coupon_list'=>$coupon_list]);
        }else{
            return json_encode(['code'=>201,'msg'=>'暂无数据']);
        }
    }

    //领取优惠券
    public function collectCoupons(){
        $user_id = input('post.user_id');
        // $user_id = 3;
        if(!is_numeric($user_id)){return json_encode(['code'=>401,'msg'=>'user_id类型错误']);}
        $coupons_id = input('post.coupons_id');
        // $coupons_id = 6;
        if(!is_numeric($coupons_id)){return json_encode(['code'=>401,'msg'=>'coupons_id类型错误']);}
        $map = "coupons_id = {$coupons_id}";
        $coupons_info = db('coupons')->field('number,receive_number,area,limits')->where($map)->find();
        if($coupons_info['number'] <= $coupons_info['receive_number']){return json_encode(['code'=>401,'msg'=>'该种优惠券已被抢光!']);}
        if($coupons_info['area'] != 0){return json_encode(['code'=>401,'msg'=>'优惠券发行区域出错']);}
        $limits = $coupons_info['limits'];
        if($limits > 0){
            $user_collect_coupons = db('coupons_use')->where("coupons_id = {$coupons_id} AND user_id = {$user_id}")->count();
            if($user_collect_coupons >= $limits){return json_encode(['code'=>401,'msg'=>'您领取该种优惠券的数目已达上限']);}
        }
        $addData = [];
        $addData['coupons_id'] = $coupons_id;
        $addData['user_id'] = $user_id;
        $addData['receive_time'] = time();
        $addData['state'] = 0;
        Db::startTrans();
        try{
            db('coupons_use')->insert($addData);
            db('coupons')->where($map)->setInc('receive_number');
            Db::commit();
        }catch(\Exception $e){
            Db::rollback();
            return json_encode(['code'=>201,'msg'=>'优惠券领取失败']);
        }
        return json_encode(['code'=>200,'msg'=>'优惠券领取成功']);
    }

    //优惠券使用 （挑选最优 优惠券）
    public function chooseCoupon(){
        $user_id = input('post.user_id');
        // $user_id = 3;
        if(!is_numeric($user_id)){return json_encode(['code'=>401,'msg'=>'user_id类型错误']);}
        $order_price = input('post.order_price');//order_price 订单金额
        // $order_price = 3000.00;
        // if($order_price)
        // 当商品为销售商品时,此时需要传入物料id
        // sale_type 1在售珠宝;2共享珠宝
        $sale_type = input('post.sale_type');
        // $sale_type = 1;
        if($sale_type){if(!is_numeric($sale_type)){return json_encode(['code'=>401,'msg'=>'sale_type类型错误']);}}  
        $scope = input('post.scope');//0会员卡;1共享商品;2所有销售商品;其它值为部分销售商品
        // $scope = 143;
        if(!is_numeric($scope)){return json_encode(['code'=>401,'msg'=>'scope类型错误']);}
        if($sale_type == 1){
            if($scope <= 1){return json_encode(['code'=>401,'msg'=>'优惠券发行区域出错']);}
        }elseif($sale_type == 2){
            if($scope != 1){return json_encode(['code'=>401,'msg'=>'优惠券发行区域出错']);}
        }
        //$where获取所有可用优惠券数组;$map获取所有不可用优惠券数组
        //state 0未使用
        if($scope >= 2){
           $where = "u.user_id = {$user_id} AND u.state = 0 AND (c.scope = {$scope} OR c.scope = 2)";
           $map = "u.user_id = {$user_id} AND u.state = 0 AND (c.scope != {$scope} AND c.scope != 2)";
        }elseif($scope == 1){
           $where = "u.user_id = {$user_id} AND u.state = 0 AND c.scope = {$scope}";
           $map = "u.user_id = {$user_id} AND u.state = 0 AND (c.scope >= 2 OR c.scope = 0)";
        }elseif($scope == 0){
           $where = "u.user_id = {$user_id} AND u.state = 0 AND c.scope = {$scope}";
           $map = "u.user_id = {$user_id} AND u.state = 0 AND c.scope >= 1";
        }
        // 第一步:找到用户账号下所有优惠券;优惠券分为可用优惠券和不可用优惠券;确保优惠券用在对应发行区域内
        $string = "u.use_id,u.coupons_id,c.name as coupons_name,c.coupons_type,c.scope,c.conditions,c.discount,c.start_time,c.settlement_time";
        $coupon_list = db('coupons_use')->alias('u')
                                        ->field($string)
                                        ->join('je_coupons c','u.coupons_id = c.coupons_id','RIGHT')
                                        ->where($where)
                                        ->order("u.receive_time desc")
                                        ->select();  
        //不可用优惠券数组
        $unavailable_coupon_list = db('coupons_use')->alias('u')
                                                    ->field($string)    
                                                    ->join('je_coupons c','u.coupons_id = c.coupons_id','RIGHT')
                                                    ->where($map)
                                                    ->order("u.receive_time desc")
                                                    ->select();
        // echo db('coupons_use')->getLastSql();echo "<br>";
        // var_dump($unavailable_coupon_list);die;
        //第二步:确保优惠券在有效期内;
        //第三步:排除不满足条件的优惠券;（消费满xx元）
        //coupons_type 1满减;2折扣; conditions满足xx金额满减/折扣;discount满减金额/折扣额度 
        $current_time = time();
        foreach($coupon_list as $key=>$value){
              if($value['settlement_time'] < $current_time){unset($coupon_list[$key]);}
              if($value['start_time'] > $current_time){
                  $unavailable_coupon_list[] = $coupon_list[$key];
                  unset($coupon_list[$key]);
              }
              //如果订单金额小于该优惠券所需最低消费金额,表示该优惠券不符合可用条件;
              if($order_price < $value['conditions']){
                  $unavailable_coupon_list[] = $coupon_list[$key];
                  unset($coupon_list[$key]);
              }
        } 

        //获取该笔订单优惠券所能优惠的金额
        foreach($coupon_list as $k=>$v){
             if($v['coupons_type'] == 2){
                  $coupon_list[$k]['discount'] = round($order_price * (1 - $v['discount']/100),2);
              } 
              $coupon_list[$k]['start_time'] = date("Y.m.d",$v['start_time']);
              $coupon_list[$k]['settlement_time'] = date("Y.m.d",$v['settlement_time']);
        }  
        foreach($unavailable_coupon_list as $u=>$c){
              $unavailable_coupon_list[$u]['start_time'] = date("Y.m.d",$c['start_time']);
              $unavailable_coupon_list[$u]['settlement_time'] = date("Y.m.d",$c['settlement_time']);
        } 
        // var_dump($coupon_list);        
        //将可用优惠券按最大优惠金额进行倒序排列
        $coupon_list = sortArrByField($coupon_list,"discount",true);
        $coupon_list_num = count($coupon_list);
        $unavailable_coupon_list_num = count($unavailable_coupon_list);
        // var_dump($coupon_list);
        // var_dump($unavailable_coupon_list);
        return json_encode([
                         'code'=>200,
                         'msg'=>'请求成功',
                         'coupon_list'=>$coupon_list,
                         'coupon_list_num'=>$coupon_list_num,
                         'unavailable_coupon_list'=>$unavailable_coupon_list,
                         'unavailable_coupon_list_num'=>$unavailable_coupon_list_num
                         ]);
    }
}